#include "BTreeNode.h"

using namespace std;

BTLeafNode::BTLeafNode()
{
	memset(buffer, 0, PageFile::PAGE_SIZE);
}

/*
 * Read the content of the node from the page pid in the PageFile pf.
 * @param pid[IN] the PageId to read
 * @param pf[IN] PageFile to read from
 * @return 0 if successful. Return an error code if there is an error.
 */
RC BTLeafNode::read(PageId pid, const PageFile& pf)
{
	memset(buffer, 0, PageFile::PAGE_SIZE);
	return pf.read(pid,buffer);
}
    
/*
 * Write the content of the node to the page pid in the PageFile pf.
 * @param pid[IN] the PageId to write to
 * @param pf[IN] PageFile to write to
 * @return 0 if successful. Return an error code if there is an error.
 */
RC BTLeafNode::write(PageId pid, PageFile& pf)
{ 
	return pf.write(pid,buffer);
}

/*
 * Return the number of keys stored in the node.
 * @return the number of keys in the node
 */
int BTLeafNode::getKeyCount()
{
	int numkeys = 0;
	memcpy(&numkeys, &buffer, sizeof(int));
	return numkeys;
}

/*
 * Insert a (key, rid) pair to the node.
 * @param key[IN] the key to insert
 * @param rid[IN] the RecordId to insert
 * @return 0 if successful. Return an error code if the node is full.
 */
RC BTLeafNode::insert(int key, const RecordId& rid)
{
	int slotSize = sizeof(RecordId) + sizeof(int);
	int totalSize = getKeyCount() * slotSize;

	if(totalSize >= PageFile::PAGE_SIZE - slotSize - sizeof(int) - sizeof(PageId)) {
		return RC_NODE_FULL;
	}

	char* iterator = &(buffer[0]);
	int i = 0;

	iterator = iterator + sizeof(int) + sizeof(PageId);

	int currentKey;
	while (iterator) {
		memcpy(&currentKey, iterator, sizeof(int));
		if(currentKey == 0) {
			break;
		}
		if (currentKey < key) {
			iterator += slotSize;
			i++;
		} else {
			break;
		}
	}

	if (&(buffer[PageFile::PAGE_SIZE]) - iterator < 20) {
		return RC_NODE_FULL;
	}

	char* tmp = (char*)malloc(PageFile::PAGE_SIZE * sizeof(char));
	memset(tmp, 0, PageFile::PAGE_SIZE);
	if(totalSize > 0 && currentKey != 0) {
		memcpy(tmp, iterator, totalSize - (slotSize * i));
		memset(iterator, 0, totalSize - (slotSize * i));
	}

	memcpy(iterator, &key, sizeof(int));
	iterator += sizeof(int);
	memcpy(iterator, &rid, sizeof(RecordId));

	iterator += sizeof(RecordId);
	if(totalSize > 0 && currentKey != 0) {
		memcpy(iterator, tmp, totalSize - (slotSize * i));
	}
	free(tmp);
	
	int currentKeyCount = getKeyCount();
	currentKeyCount++;
	iterator = &(buffer[0]);
	memcpy(iterator, &currentKeyCount, sizeof(int));

	return 0;
}

/*
 * Insert the (key, rid) pair to the node
 * and split the node half and half with sibling.
 * The first key of the sibling node is returned in siblingKey.
 * @param key[IN] the key to insert.
 * @param rid[IN] the RecordId to insert.
 * @param sibling[IN] the sibling node to split with. This node MUST be EMPTY when this function is called.
 * @param siblingKey[OUT] the first key in the sibling node after split.
 * @return 0 if successful. Return an error code if there is an error.
 */
RC BTLeafNode::insertAndSplit(int key, const RecordId& rid, 
                              BTLeafNode& sibling, int& siblingKey)
{
	int slotSize = sizeof(RecordId) + sizeof(int);
	int totalSize = getKeyCount() * slotSize;
	int i = 0;

	char* iterator = &(buffer[0]);
	iterator = iterator + sizeof(int) +  sizeof(PageId);

	for( ; i < (getKeyCount() / 2) ; i++) {
		iterator += slotSize;
	}
	
	char* tmp = (char*)malloc(1024*sizeof(char));
	char* head = tmp;
	
	memset(tmp, 0, 1024*sizeof(char));
	memcpy(tmp, iterator, totalSize - (slotSize * (getKeyCount()/2)));

	memset(iterator, 0, totalSize - (slotSize * (getKeyCount()/2)));
	int newKey = getKeyCount() / 2;
	memcpy(buffer, &newKey, sizeof(int));

	int k;
	RecordId rit;
	memcpy(&k, tmp, sizeof(int));
	while(k!=0) {
		tmp += sizeof(int);
		memcpy(&rit, tmp, sizeof(RecordId));
		tmp += sizeof(RecordId);
		if(rit.sid == 0 && rit.pid == 0 && k != 272) {
			int q = rit.sid;
		}
		if( sibling.insert(k, rit) != 0 ) {
			free(head);
			return RC_FILE_WRITE_FAILED;
		}
		memcpy(&k, tmp, sizeof(int));
	}

	free(head);

	RecordId r;
	if( sibling.readEntry(0, siblingKey, r) != 0) {
		return RC_FILE_READ_FAILED;
	}

	if(key < siblingKey) {
		if( insert(key, rid) != 0 ) {
			return RC_FILE_WRITE_FAILED;
		}
	} else {
		if( sibling.insert(key, rid) != 0 ) {
			return RC_FILE_WRITE_FAILED;
		}
	}

	if( sibling.readEntry(0, siblingKey, r) != 0) {
		return RC_FILE_READ_FAILED;
	}

	return 0; 
}

/*
 * Find the entry whose key value is larger than or equal to searchKey
 * and output the eid (entry number) whose key value >= searchKey.
 * Remeber that all keys inside a B+tree node should be kept sorted.
 * @param searchKey[IN] the key to search for
 * @param eid[OUT] the entry number that contains a key larger than or equalty to searchKey
 * @return 0 if successful. Return an error code if there is an error.
 */
RC BTLeafNode::locate(int searchKey, int& eid)
{
	int slotSize = sizeof(RecordId) + sizeof(int);
	int totalSize = getKeyCount() * slotSize;
	char* iterator = &(buffer[0]);
	int currentKey;
	int i = 0;

	iterator += sizeof(int);

	while(iterator) {
		memcpy(&currentKey, iterator, sizeof(int));
		if(currentKey >= searchKey || currentKey == 0) {
			eid = i;
			break;
		}
		i++;
		iterator += slotSize;
	}

	return 0; 
}

/*
 * Read the (key, rid) pair from the eid entry.
 * @param eid[IN] the entry number to read the (key, rid) pair from
 * @param key[OUT] the key from the entry
 * @param rid[OUT] the RecordId from the entry
 * @return 0 if successful. Return an error code if there is an error.
 */
RC BTLeafNode::readEntry(int eid, int& key, RecordId& rid)
{
	int slotSize = sizeof(RecordId) + sizeof(int);
	int totalSize = getKeyCount() * slotSize;
	char* iterator = &(buffer[0]);
	int i = 0;

	iterator += sizeof(int);
	iterator += sizeof(PageId);
	while(iterator && i < eid) {
		iterator += slotSize;
		i++;
	}
	memcpy(&key, iterator, sizeof(int));
	iterator += sizeof(int);
	memcpy(&rid, iterator, sizeof(RecordId));

	return 0; 
}

/*
 * Return the pid of the next slibling node.
 * @return the PageId of the next sibling node 
 */
PageId BTLeafNode::getNextNodePtr()
{
	PageId pid;

	char* iterator = &(buffer[0]);
	iterator += sizeof(int);

	memcpy(&pid, iterator, sizeof(PageId));

	return pid; 
}

/*
 * Set the pid of the next slibling node.
 * @param pid[IN] the PageId of the next sibling node 
 * @return 0 if successful. Return an error code if there is an error.
 */
RC BTLeafNode::setNextNodePtr(PageId pid)
{
	char* iterator = &(buffer[0]);
	iterator += sizeof(int);

	memcpy(iterator, &pid, sizeof(PageId));

	return 0; 
}

BTNonLeafNode::BTNonLeafNode() {
	memset(buffer, 0, PageFile::PAGE_SIZE);
}

/*
 * Read the content of the node from the page pid in the PageFile pf.
 * @param pid[IN] the PageId to read
 * @param pf[IN] PageFile to read from
 * @return 0 if successful. Return an error code if there is an error.
 */
RC BTNonLeafNode::read(PageId pid, const PageFile& pf)
{ 
	return pf.read(pid,buffer);
}
    
/*
 * Write the content of the node to the page pid in the PageFile pf.
 * @param pid[IN] the PageId to write to
 * @param pf[IN] PageFile to write to
 * @return 0 if successful. Return an error code if there is an error.
 */
RC BTNonLeafNode::write(PageId pid, PageFile& pf)
{ 
	return pf.write(pid,buffer);
}

/*
 * Return the number of keys stored in the node.
 * @return the number of keys in the node
 */
int BTNonLeafNode::getKeyCount()
{
	int numkeys = 0;
	memcpy(&numkeys, &buffer, sizeof(int));
	return numkeys;
}


/*
 * Insert a (key, pid) pair to the node.
 * @param key[IN] the key to insert
 * @param pid[IN] the PageId to insert
 * @return 0 if successful. Return an error code if the node is full.
 */
RC BTNonLeafNode::insert(int key, PageId pid)
{ 
	int slotSize = sizeof(PageId) + sizeof(int);
	int totalSize = getKeyCount() * slotSize;
	char* iterator = &(buffer[0]);
	int i = 0;

	if(totalSize >= PageFile::PAGE_SIZE - slotSize) {
		return RC_NODE_FULL;
	}

	iterator += slotSize;

	int currentKey;
	memcpy(&currentKey, iterator, sizeof(int));
	
	while (currentKey != 0 || currentKey >= key) {
		if (currentKey < key) {
			iterator += slotSize;
			i++;
		}
		memcpy(&currentKey, iterator, sizeof(int));
	}

	if(currentKey == key) {
		iterator += sizeof(int);
		memcpy(iterator, &pid, sizeof(PageId));
		return 0;
	}

	if (iterator == &(buffer[PageFile::PAGE_SIZE]))
		return RC_FILE_WRITE_FAILED;

	char* tmp = (char*) malloc(PageFile::PAGE_SIZE * sizeof(char));
	memset(tmp, 0, PageFile::PAGE_SIZE);


	if(totalSize > 0 && currentKey != 0) {
		memcpy(tmp, iterator, totalSize - (slotSize * i));
		memset(iterator, 0, totalSize - (slotSize * i));
	}
	memcpy(iterator, &key, sizeof(int));
	iterator += sizeof(int);
	memcpy(iterator, &pid, sizeof(PageId));
	iterator += sizeof(PageId);
	if(totalSize > 0 && currentKey != 0) {
		memcpy(iterator, tmp, totalSize - (slotSize * i));
	}
	free(tmp);
	
	int currentKeyCount = getKeyCount() + 1;
	iterator = &(buffer[0]);
	memcpy(iterator, &currentKeyCount, sizeof(int));

	return 0;
}

RC BTNonLeafNode::readEntry(int eid, int& key) {
	int slotSize = sizeof(PageId) + sizeof(int);
	int totalSize = getKeyCount() * slotSize;
	int i = 0;

	char* iterator = &(buffer[0]);
	iterator += sizeof(int);

	while(iterator) {
		iterator += sizeof(PageId);
		if(i == eid) {
			memcpy(&key, iterator, sizeof(int));
			break;
		}
		iterator += slotSize;
	}

	return 0;
}


/*
 * Insert the (key, pid) pair to the node
 * and split the node half and half with sibling.
 * The middle key after the split is returned in midKey.
 * @param key[IN] the key to insert
 * @param pid[IN] the PageId to insert
 * @param sibling[IN] the sibling node to split with. This node MUST be empty when this function is called.
 * @param midKey[OUT] the key in the middle after the split. This key should be inserted to the parent node.
 * @return 0 if successful. Return an error code if there is an error.
 */
RC BTNonLeafNode::insertAndSplit(int key, PageId pid, BTNonLeafNode& sibling, int& midKey)
{ 
	int slotSize = sizeof(PageId) + sizeof(int);
	int totalSize = getKeyCount() * slotSize;
	int i = 0;

	char* iterator = &(buffer[0]);
	iterator += sizeof(int);

	for( ; i < (getKeyCount() / 2) ; i++ ) {
		iterator += slotSize;
	}

	char* tmp = (char*) malloc(PageFile::PAGE_SIZE * sizeof(char));
	char* head = tmp;
	
	memset(tmp, 0, 1024*sizeof(char));
	memcpy(tmp, iterator, totalSize - (slotSize * (getKeyCount() / 2)));
	
	memset(iterator, 0, totalSize - (slotSize * (getKeyCount() / 2)));
	int newKey = getKeyCount() / 2;
	memcpy(buffer, &newKey, sizeof(int));
	
	int k;
	PageId p;
	memcpy(&k, tmp, sizeof(int));
	
	while(k != 0) {
		tmp += sizeof(int);
		memcpy(&p, tmp, sizeof(PageId));
		tmp += sizeof(PageId);
		if( sibling.insert(k, p) != 0) {
			free(head);
			return RC_FILE_WRITE_FAILED;
		}
		memcpy(&k, tmp, sizeof(int));
	}

	free(head);

	if( sibling.readEntry(0, midKey) != 0 ) {
		return RC_FILE_READ_FAILED;
	}

	if(key < midKey) {
		if( insert(key, pid) != 0 ){
			return RC_FILE_WRITE_FAILED;
		}
	} else {
		if( sibling.insert(key, pid) != 0 ) {
			return RC_FILE_WRITE_FAILED;
		}
	}

	return 0; 
}

/*
 * Given the searchKey, find the child-node pointer to follow and
 * output it in pid.
 * @param searchKey[IN] the searchKey that is being looked up.
 * @param pid[OUT] the pointer to the child node to follow.
 * @return 0 if successful. Return an error code if there is an error.
 */
RC BTNonLeafNode::locateChildPtr(int searchKey, PageId& pid)
{
	int slotSize = sizeof(PageId) + sizeof(int);
	int totalSize = getKeyCount() * slotSize;
	char* iterator = &(buffer[0]) + 2*sizeof(int);
	int currentKey;

	while(iterator) {
		memcpy(&currentKey, iterator, sizeof(int));
		if(currentKey != 0 && currentKey < searchKey) {
			iterator += sizeof(int);
		} else {
			iterator -= sizeof(PageId);
			memcpy(&pid, iterator, sizeof(PageId));
			break;
		}
		iterator += slotSize;
	}
 
	return 0;	
}

/*
 * Initialize the root node with (pid1, key, pid2).
 * @param pid1[IN] the first PageId to insert
 * @param key[IN] the key that should be inserted between the two PageIds
 * @param pid2[IN] the PageId to insert behind the key
 * @return 0 if successful. Return an error code if there is an error.
 */
RC BTNonLeafNode::initializeRoot(PageId pid1, int key, PageId pid2)
{
	char* iterator = &(buffer[0]);
	int k = 1;
	iterator += sizeof(int);

	memcpy(iterator, &pid1, sizeof(PageId));
	iterator += sizeof(PageId);
	memcpy(iterator, &key, sizeof(int));
	iterator += sizeof(int);
	memcpy(iterator, &pid2, sizeof(PageId));

	memcpy(buffer, &k, sizeof(int));

	return 0; 
}
